package com.suyafei.util;

import com.suyafei.model.LoginUser;
import io.jsonwebtoken.*;

import java.util.Date;

/**
 * @program: suyafei-1024-shop
 * @description
 * @author: luffy
 * @create: 2021-02-26 16:13
 */
public class JWTUtil {


    /**
     * token过期时间（正常是7天）
     */
    private static final long EXPIRE = 1000 * 60 * 60 * 24 * 7 * 100;
    /**
     * 加密的秘钥
     */
    private static final String SECRET = "xdclass.net666";
    /**
     * 令牌前缀
     */
    private static final String TOKEN_PREFIX = "xdclass.net666";

    /**
     * subject
     */
    private static final String SUBJECT = "xdclass";

    /**
     * 格局用户信息生成token
     * @param loginUser
     * @return
     */
    public static String geneJsonWebToken(LoginUser loginUser) {

        if (loginUser == null) {
            throw new NullPointerException("对象不能为空");
        }

        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("head_img", loginUser.getHeadImg())
                .claim("id", loginUser.getId())
                .claim("name", loginUser.getName())
                .claim("mail", loginUser.getMail())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();

        token = TOKEN_PREFIX + token;
        return token;
    }

    public static Claims chekJWT(String token) {
        try {
            final Claims claims = Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token.replaceAll(TOKEN_PREFIX, "")).getBody();
            return claims;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
